//
//  DFLikeCommentView.m
//  DFTimelineView
//
//  Created by Allen Zhong on 15/9/28.
//  Copyright (c) 2015年 Datafans, Inc. All rights reserved.
//

#import "DFLikeCommentView.h"
#import "MLLabel+Size.h"
#import "DFLineLikeItem.h"
#import "DFLineCommentItem.h"
#import "Const.h"
#import "DFBigImageView.h"
//#import <MLLinkClickLabel.h>

#import "MLClickColorLinkLabel.h"


#define TopMargin 10
#define BottomMargin 6


#define LikeLabelFont [UIFont systemFontOfSize:14]

#define LikeLabelLineHeight 1.1f

#define LikeIconLeftMargin 8
#define LikeIconTopMargin 8
#define LikeIconSize 25
#define LikeIconViewHeight 33
#define LikeLabelIconSpace 5
#define LikeLabelRightMargin 10
#define CommentShowMaxNum 5
#define LikesMaxCount 5
#define CommentLabelFont [UIFont systemFontOfSize:14]

#define CommentLabelLineHeight 1.2f


#define CommentLabelMargin 10

#define LikeCommentSpace 5

#define LinkLabelTag 100
#define Margin 15
#define BodyMaxWidth [UIScreen mainScreen].bounds.size.width - 2*Margin

@interface DFLikeCommentView()<MLLinkClickLabelDelegate,CAAnimationDelegate>


@property (nonatomic, strong) UIImageView *likeCmtBg;

@property (strong, nonatomic) DFBigImageView *likeIconView;

@property (strong, nonatomic) UILabel *likeLabel;
@property (strong, nonatomic) UILabel *likeCountLabel;

@property (strong, nonatomic) UIView *divider;

@property (strong, nonatomic) NSMutableArray *commentLabels;

@property (strong, nonatomic) NSMutableArray *likesArray;

@property (assign, nonatomic)float keyboardHeight;

@property (assign, nonatomic)BOOL status;

@end



@implementation DFLikeCommentView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        _commentLabels = [NSMutableArray array];
        
        [self initView];
    }
    return self;
}


-(void) initView
{
    
//    [self registerForKeyboardNotifications];
    CGFloat x,y,width,height;
    
    if (_likeCmtBg == nil) {
        x = 0;
        y = 0;
        width = self.frame.size.width;
        height = self.frame.size.height;
        
        _likeCmtBg = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, width, height)];
//        UIImage *image = [UIImage imageNamed:@"LikeCmtBg"];
        UIImage *image = [UIImage imageNamed:@""];
        image = [image resizableImageWithCapInsets:UIEdgeInsetsMake(20, 30, 10, 10) resizingMode:UIImageResizingModeStretch];
        _likeCmtBg.image = image;
        [self addSubview:_likeCmtBg];
    }
    if (_likeLabel == nil) {
       
        y = LikeIconTopMargin;
        width = BodyMaxWidth;
        height = LikeIconViewHeight;
        _likeLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, y, width, height)];
        _likeLabel.userInteractionEnabled = YES;
        [self addSubview:_likeLabel];
    }
    
    if (_likeIconView == nil) {
        x = LikeLabelIconSpace;
        y = 0;
        width = LikeIconSize;
        height = width;
        _likeIconView = [[DFBigImageView alloc] initWithFrame:CGRectMake(x, y, width, height)];
        [_likeIconView.imageButton addTarget:self action:@selector(likeImgTap:) forControlEvents:UIControlEventTouchUpInside];
        _likeIconView.userInteractionEnabled = YES;
        [_likeLabel addSubview:_likeIconView];
    }
    for (int i = 0; i<6; i++) {
        x = CGRectGetMaxX(_likeIconView.frame)+15;
        float spacing = 10;
        y = 0;
        width = 30;
        height = 30;
        DFBigImageView*imgView = [[DFBigImageView alloc]initWithFrame:CGRectMake((30+spacing)*i+x, 0, 30, 30)];
        imgView.layer.cornerRadius = 15;
        imgView.layer.masksToBounds = YES;
        imgView.hidden = YES;
        imgView.imageButton.tag = 10+i;
        imgView.tag = 100+i;
        [_likeLabel addSubview:imgView];
        
    }
    if (_likeCountLabel == nil) {
        x = BodyMaxWidth-LikeIconViewHeight;
        width =LikeIconViewHeight;
        height = width;
        _likeCountLabel = [[UILabel alloc]initWithFrame:CGRectZero];
        _likeCountLabel.backgroundColor = [UIColor grayColor];
        _likeCountLabel.textColor = [UIColor whiteColor];
        _likeCountLabel.textAlignment = NSTextAlignmentCenter;
        _likeCountLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:15];
        _likeCountLabel.hidden = YES;
        [_likeLabel addSubview:_likeCountLabel];
    }
//    if (_divider == nil) {
//        _divider = [[UIView alloc] initWithFrame:CGRectZero];
//        _divider.backgroundColor = [UIColor colorWithWhite:225/255.0 alpha:1.0];
//        [self addSubview:_divider];
//    }
}

- (void)likeUserImgAction:(UIButton *)sender
{
    NSLog(@"点击点赞用户头像");
   DFLineLikeItem *item =  [self.likesArray objectAtIndex:sender.tag -200];
    
    if (_delegate && [_delegate respondsToSelector:@selector(onClickUser:)]) {
        [_delegate onClickUser:item.userId];
    }
}

- (void)likeImgTap:(UIButton *)sender
{
//    点赞状态00点赞01取消点赞
    if (sender.selected == NO) {
        sender.selected = YES;
        self.status = NO;
        [self requestDianZanWithContentId:self.contentId type:self.status];
        }else{
            
        sender.selected = NO ;
        self.status = YES ;
            [self requestDianZanWithContentId:self.contentId type:self.status];
    }
   
}

#pragma mark - DFLikeCommentViewDelegate

- (void)requestDianZanWithContentId:(NSString *)contentId type:(BOOL)type{
    DYBaseRequest *request = [DYBaseRequest new];
    NSString *content_id = contentId;
    NSString *status = @"";
    if (self.status) {
//        点赞状态00点赞01取消点赞
        status = @"01";
    }else{
        status = @"00";
    }
    NSString *url = [NSString stringWithFormat:@"%@/hyContent/setContentLike?content_id=%@&status=%@", APIYIGOU, content_id,status];
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
       self.status = !self.status;
        NSData *JSONData = [request.responseString dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
        
        UILabel *label = [[UILabel alloc]init];
        label.frame = self.likeIconView.frame;
        label.textColor = [UIColor redColor];
        label.font = [UIFont systemFontOfSize:13];
        if (self.status) {
            self.likeIconView.imageView.image = [UIImage imageNamed:@"点赞"];
            self.likeIconView.imageButton.selected = NO;
            [ViewFactory showSuccess:@"点赞成功"];
            label.text = @"+1";
        }else{
            self.likeIconView.imageView.image = [UIImage imageNamed:@"取消点赞"];
            self.likeIconView.imageButton.selected = YES;
            [ViewFactory showSuccess:@"取消点赞成功"];
            label.text = @"-1";
        }
    
    [UIView animateWithDuration:1.0 animations:^{
            
        label.frame =CGRectMake(self.likeIconView.frame.origin.x, self.likeIconView.frame.origin.y-20, self.likeIconView.frame.size.width, self.likeIconView.frame.size.height);
            label.transform = CGAffineTransformMakeScale(1.3, 1.3);
            label.alpha = 1.0;
            [self addSubview:label];
        } completion:^(BOOL finished) {
            
            if (finished) {
                
                [label removeFromSuperview];
            }
            [self gainNewLikeCount];
            
        }];
        
    } error:^(YTKBaseRequest *request) {
        NSData *JSONData = [request.responseString dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
        [ViewFactory showErrorStrMsg:[responseJSON objectForKey:@"message"]];
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        
    }];
    
}
- (void)gainNewLikeCount{
    
    //获取所有点赞信息
    if (_delegate && [_delegate respondsToSelector:@selector(onClickLikeType:)]) {
        [_delegate onClickLikeType:self.status];
    }
    
}

-(void)layoutSubviews
{
    CGFloat x,y,width,height;
    x = 0;
    y = 0;
    width = self.frame.size.width;
    height = self.frame.size.height;
    
    _likeCmtBg.frame = CGRectMake(x, y, width, height);
}


-(void)updateWithItem:(DFBaseLineItem *)item
{
    CGFloat x, y, width, height;
    self.likeCountLabel.hidden = YES;
    self.contentId = item.content_id;
    self.userId = item.user_id;
    _likeIconView.imageView.image =  [UIImage imageNamed:@"取消点赞"];
    _likeIconView.imageButton.selected = NO;
    for (DFLineLikeItem *tmpItem in item.likes) {
        NSLog(@"tmpItem:%@",tmpItem.userId);
        NSLog(@"tmpItem:%@",[UserData userid]);
        if ( [tmpItem.userId isEqualToString:[UserData userid]]) {
            _likeIconView.imageView.image =  [UIImage imageNamed:@"点赞"];
            _likeIconView.imageButton.selected = YES;
        }
    }
        x = CGRectGetMaxX(_likeIconView.frame)+LikeLabelIconSpace;
        y = TopMargin;
        width = self.frame.size.width - x - LikeLabelRightMargin;
        self.likesArray = [NSMutableArray new];
    for (int i = 0; i<LikesMaxCount ; i++) {
        DFBigImageView *imgView = [self viewWithTag:100+i];
        imgView.hidden = YES;
    }
        self.likesArray = item.likes;
   NSInteger count=item.likes.count>LikesMaxCount?LikesMaxCount:(item.likes.count);
        for (int i = 0; i<count; i++) {
            DFLineLikeItem *dic = [item.likes objectAtIndex:i];
            NSString *str = dic.head_url;
             DFBigImageView*imgView = [self viewWithTag:100+i];
            imgView.hidden = NO;
            NSString *newStr = [NSString stringWithFormat:@"%@?imageView2/0/w/%@/h/%@",str,@"30",@"30"];
            [imgView.imageView sd_setImageWithURL:[NSURL URLWithString:newStr]];
            imgView.userInteractionEnabled = YES;
            [imgView.imageButton addTarget:self action:@selector(likeUserImgAction:) forControlEvents:UIControlEventTouchUpInside];
            imgView.imageButton.tag = 200+i;
            [item.likesUserImgArray addObject:str];
        }
     DFBigImageView*imgView = [self viewWithTag:100+count-1];
    x = CGRectGetMaxX(imgView.frame);
    _likeCountLabel.frame = CGRectMake(x+10, 0, 30, 30);
    if (item.likes.count>0) {
        _likeCountLabel.hidden = NO;
        _likeCountLabel.text = [NSString stringWithFormat:@"%lu",(unsigned long)item.likes.count];
    }
   
    if (item.comments.count > 0) {
        
            //显示分割线
        y = CGRectGetMaxY(_likeLabel.frame) + LikeCommentSpace;

        CGFloat sumHeight = TopMargin;
        
    sumHeight = CGRectGetMaxY(_likeLabel.frame) + LikeCommentSpace;
        
        NSUInteger labelCount = _commentLabels.count;
        
        for (int i=0; i<labelCount; i++) {
            MLLinkClickLabel *label = [_commentLabels objectAtIndex:i];
            label.attributedText = nil;
            label.frame = CGRectZero;
            label.hidden = !(i<item.comments.count);
        }
        
       
        for (int i=0;i<item.commentStrArray.count;i++) {
            
            MLLinkClickLabel *label;
            
            if ( labelCount > 0 && i < labelCount) {
                label = [_commentLabels objectAtIndex:i];
            }else{
                label = [self createLinkLabel];
                [_commentLabels addObject:label];
                [self addSubview:label];
            }
            
            DFLineCommentItem *commentItem = [item.comments objectAtIndex:i];
            
            label.hidden = NO;
            NSAttributedString *str = [item.commentStrArray objectAtIndex:i];
            label.attributedText = str ;
            label.uniqueId = commentItem.commentId;
            [label sizeToFit];
            
            width = self.frame.size.width - 2*CommentLabelMargin;
            CGSize size = [MLLabel getViewSize:label.attributedText maxWidth:width font:CommentLabelFont lineHeight:CommentLabelLineHeight lines:0];
            x = CommentLabelMargin;
            y = sumHeight;
            height = size.height;
            sumHeight+=height;
            label.frame = CGRectMake(x, y, width, height);
        }
       
    }else{
        for (int i=0; i<_commentLabels.count; i++) {
            MLLinkClickLabel *label = [_commentLabels objectAtIndex:i];
            label.attributedText = nil;
            label.frame = CGRectZero;
            label.hidden = YES;
        }
        
    }
    if (_commentLabels.count>CommentShowMaxNum) {
        for (int i=CommentShowMaxNum; i<_commentLabels.count; i++) {
            MLLinkClickLabel *label = [_commentLabels objectAtIndex:i];
            label.attributedText = nil;
            label.frame = CGRectZero;
            label.hidden = YES;
        }
    }

}



-(MLClickColorLinkLabel *) createLinkLabel
{
    
    MLClickColorLinkLabel *lable = [[MLClickColorLinkLabel alloc] initWithFrame:CGRectZero];
    lable.clickDelegate = self;
    lable.textColor = [UIColor grayColor];
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
    [lable addGestureRecognizer:longPress];
    
    lable.tag = LinkLabelTag;
    
    
    lable.font = LikeLabelFont;
    lable.numberOfLines = 0;
    lable.adjustsFontSizeToFitWidth = NO;
    lable.textInsets = UIEdgeInsetsZero;
    
    lable.dataDetectorTypes = MLDataDetectorTypeAll;
    lable.allowLineBreakInsideLinks = NO;
    lable.linkTextAttributes = nil;
    lable.activeLinkTextAttributes = nil;
    lable.lineHeightMultiple = CommentLabelLineHeight;
    lable.linkTextAttributes = @{NSForegroundColorAttributeName: [UIColor blackColor]};
    
    __block DFLikeCommentView *likeCommentView = self;
    
    [lable setDidClickLinkBlock:^(MLLink *link, NSString *linkText, MLLinkLabel *label) {
        
        if (_delegate != nil && [_delegate respondsToSelector:@selector(onClickUser:)]) {
            
//            NSUInteger userId = [link.linkValue integerValue];
            [likeCommentView.delegate onClickUser:link.linkValue];
        }
    }];
    
    
    return lable;
    
}

-(void)longPress:(UITapGestureRecognizer*)recognizer
{
    NSLog(@"recognizer.view:%@",recognizer.self.view);
    UILabel *label = (UILabel *)recognizer.self.view;
    NSLog(@"长按了Label");
    
}

-(void)onClickOutsideLink:(NSString *)uniqueId
{
    if (_delegate && [_delegate respondsToSelector:@selector(onClickComment:)]) {
        [_delegate onClickComment:uniqueId];
    }
}


+(CGFloat)getHeight:(DFBaseLineItem *)item maxWidth:(CGFloat)maxWidth
{
    CGFloat height = TopMargin;
    
    height+= LikeIconViewHeight;
    
    if (item.comments.count > 0) {
        
        if (item.comments.count>CommentShowMaxNum) {
            CGFloat width = maxWidth - CommentLabelMargin*2;
            
            NSMutableArray *commentStrArray = item.commentStrArray;
            for (int i = 0; i<CommentShowMaxNum; i++) {
                NSMutableAttributedString *str = [commentStrArray objectAtIndex:i];
                CGSize textSize = [MLLinkLabel getViewSize:str maxWidth:width font:CommentLabelFont lineHeight:CommentLabelLineHeight lines:0];
                height+= textSize.height;
            }
        }else{
            CGFloat width = maxWidth - CommentLabelMargin*2;
            
            NSMutableArray *commentStrArray = item.commentStrArray;
            
            for (NSMutableAttributedString *str in commentStrArray) {
                CGSize textSize = [MLLinkLabel getViewSize:str maxWidth:width font:CommentLabelFont lineHeight:CommentLabelLineHeight lines:0];
                height+= textSize.height;
            }
        }
    }
    height+=BottomMargin;
    
    return height;
}
//- (void) keyboardWasShown:(NSNotification *) notif
//{
//    NSDictionary *info = [notif userInfo];
//    NSValue *value = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
//    CGSize keyboardSize = [value CGRectValue].size;
//    
//    NSLog(@"keyBoard:%f", keyboardSize.height);  //216
//    ///keyboardWasShown = YES;
//    self.keyboardHeight = keyboardSize.height;
//}
//- (void) keyboardWasHidden:(NSNotification *) notif
//{
//    NSDictionary *info = [notif userInfo];
//    
//    NSValue *value = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
//    CGSize keyboardSize = [value CGRectValue].size;
//    NSLog(@"keyboardWasHidden keyBoard:%f", keyboardSize.height);
//    // keyboardWasShown = NO;
//}
//
//- (void) registerForKeyboardNotifications
//{
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
//    
//    [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(keyboardWasHidden:) name:UIKeyboardDidHideNotification object:nil];
//}
@end
